<template>
<div class="editUser">
  <el-form ref="userForm" :model="userForm" :rules="rules" label-width="80px" class="userForm">
    <el-col :span="18">
      <el-form-item label="个人头像">
        <img v-if="!userForm.avatar" :src="env.baseUrl+'/sys/member/avatar/m/'+ userForm.uid + '?' + Math.random()" class="avatar">
        <img v-else :src="userForm.avatar" class="avatar">
        <el-upload 
          v-if="userDetail.avatarUrl.edit"
          class="avatar-uploader"
          :action="env.baseUrl + '/file/upload'"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :headers="headers">
          <span slot="trigger" class="upload">上传头像</span>
          <span class="tips">（格式：JPG、JPEG、PNG大小不超过3M）</span>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" placeholder="英文、数字、或者英文+数字" :disabled="!userDetail.username.edit"></el-input>
      </el-form-item>
      <el-form-item label="密码" v-if="userDetail.passwd.edit||userDetail.passwd.change">
        <el-button @click="dialogVisible2=true">修改密码</el-button>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input v-model="userForm.realname" :disabled="!userDetail.realname.edit"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="userForm.phone" :disabled="!userDetail.phone.edit"></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="userForm.email" :disabled="!userDetail.email.edit"></el-input>
      </el-form-item>
      <el-form-item label="所属架构" prop="groupId">
        <el-select v-if="!userDetail.groupId.edit" placeholder="请选择" v-model="userForm.groupName" :disabled="!userDetail.groupId.edit">
        </el-select>
        <el-select v-else placeholder="请选择" v-model="userForm.groupId">
          <el-option v-for="item in groups" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="!userDetail.characterId.edit" label="角色">
        <el-select placeholder="请选择" v-model="userForm.characterName" disabled>
        </el-select>
      </el-form-item>
      <el-form-item v-else label="角色" prop="characterId">
        <el-select placeholder="请选择" v-model="userForm.characterId">
          <el-option v-for="item in roles" :key="item.gid" :label="item.cName" :value="item.cid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限" prop="authority" v-if="userDetail.authority.edit">
        <el-button @click="handleSetAuth">赋予权限</el-button>
      </el-form-item>
    </el-col>
  </el-form>
  <div class="bottom">
    <el-button v-if="canSave" type="primary" style="width:100px" @click="submitForm('userForm')" :loading="saving">保存</el-button>
  </div>
  <!-- 权限弹层 -->
  <el-dialog title="权限设置" :visible.sync="dialogVisible" custom-class="auth-dialog" @open="handleOpenDialog">
    <auth-list ref="AList" :auths="authData" :roleAuth="userForm.authority"></auth-list>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSaveAuth">保存</el-button>
    </div>
  </el-dialog>
  <!-- 修改密码弹层 -->
  <el-dialog title="修改密码" :visible.sync="dialogVisible2" width="30%" @open="$refs.pwForm.resetFields()">
    <el-form ref="pwForm" :model="pwForm" :rules="pwRules" label-width="80px">
      <el-form-item v-if="!userDetail.passwd.reset" prop="old" label="旧密码" required>
        <el-input placeholder="请输入原始密码" v-model="pwForm.old"></el-input>
      </el-form-item>
      <el-form-item prop="new" label="新密码">
        <el-input placeholder="8位及以上数字+字母组合" type="password" v-model="pwForm.new"></el-input>
      </el-form-item>
      <el-form-item prop="check" label="确认密码">
        <el-input placeholder="确认密码" type="password" v-model="pwForm.check"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible2 = false">取 消</el-button>
      <el-button type="primary" @click="userDetail.passwd.reset?handleResetPW():handleChangePW()">保存</el-button>
    </div>
  </el-dialog>
</div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  import authList from '@/components/common/sysManage/authList'
  import env from '@/config/env'
  export default {
    data () {
      const validatePW = (rule, value, callback) => {
        if (value !== this.pwForm.new) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        userForm: {
          uid: this.$route.params.uid,
          avatar: '',
          username: '',
          password: '',
          realname: '',
          email: '',
          phone: '',
          groupId: '',
          characterId: '',
          characterName: '',
          authority: ''
        },
        rules: {
          password: [{required: true, message: '请输入密码', trigger: 'blur'},
                     {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/, message: '密码不符合规则', trigger: 'blur'}],
          realname: {required: true, message: '请输入真实姓名', trigger: 'blur'},
          email: [{required: true, message: '请输入邮箱', trigger: 'blur'},
                  {pattern: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, message: '邮箱不合法', trigger: 'blur'}],
          phone: [{required: true, message: '请输入手机号码', trigger: 'blur'},
                  {pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
          groupId: {required: true, message: '请选择所属架构'},
          characterId: {required: true, message: '请选择所属角色'}
        },
        pwForm: {
          old: '',
          new: '',
          check: ''
        },
        pwRules: {
          old: [{required: true, trigger: 'blur', message: '请输入密码'}],
          new: [{required: true, trigger: 'blur', message: '请输入密码'},
                {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$/, trigger: 'blur', message: '密码为8位及以上的数字+字母组合！'}],
          check: [{required: true, trigger: 'blur', message: '请再次输入密码'},
                  {validator: validatePW, trigger: 'blur'}]
        },
        fileList: [],
        dialogVisible: false,
        dialogVisible2: false,
        saving: false
      }
    },
    mounted () {
      this.init()
    },
    components: {
      authList
    },
    watch: {
      $route () {
        this.init()
      }
    },
    computed: {
      ...mapState({
        authData: state => state.sysManage.authList,
        groups: state => state.groupMenu,
        roles: state => state.sysManage.roles,
        userDetail: state => state.sysManage.userDetail
      }),
      // 设置上传文件的头部
      headers () {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      },
      env () {
        return env
      },
      canSave () {
        for (let i in this.userDetail) {
          if (this.userDetail[i].edit) {
            return true
          }
        }
        return false
      }
    },
    methods: {
      ...mapActions(['getGroupMenu', 'getRoleList2', 'getAuthList', 'editUser', 'getUserDetail2', 'resetUserPSW', 'changeUserPSW']),
      init () {
        this.getUserDetail2(this.$route.params.uid)
          .then(() => {
            this.userForm = {
              ...this.userForm,
              uid: this.userDetail.uid.value,
              avatar: this.userDetail.avatarUrl.value,
              username: this.userDetail.username.value,
              realname: this.userDetail.realname.value,
              email: this.userDetail.email.value,
              phone: this.userDetail.phone.value,
              groupId: this.userDetail.groupId.value,
              groupName: this.userDetail.groupName.value,
              characterId: this.userDetail.characterId.value,
              characterName: this.userDetail.characterName.value,
              authority: this.userDetail.authority.value
            }
          })
        this.getAuthList()
        this.getGroupMenu()
        this.getRoleList2()
      },
      // 保存选中的权限
      handleSaveAuth () {
        this.userForm.authority = this.$refs.AList.checkedList.join(',')
        this.dialogVisible = false
        this.$refs.userForm.validateField('authority')
      },
      handleSetAuth () {
        if (this.$refs.AList) {
          this.$refs.AList.checkedList = this.userForm.authority.split(',').map(x => +x)
        }
        this.dialogVisible = true
      },
      // 重置密码
      handleResetPW () {
        this.$refs['pwForm'].validate(valid => {
          if (valid) {
            this.resetUserPSW({
              uid: this.$route.params.uid,
              passwd: this.pwForm.new
            }).then(res => {
              if (res.data.code === 1) {
                this.$message.success(res.data.msgZ)
                this.dialogVisible2 = false
              }
            })
          }
        })
      },
      // 修改密码
      handleChangePW () {
        this.$refs['pwForm'].validate(valid => {
          if (valid) {
            this.changeUserPSW({
              old: this.pwForm.old,
              new: this.pwForm.new
            }).then(res => {
              if (res.data.code === 1) {
                this.$message.success(res.data.msgZ)
                this.dialogVisible2 = false
              }
            })
          }
        })
      },
      // 上传成功
      handleAvatarSuccess (res, file) {
        this.userForm.avatar = res.data
      },
      // 头像上传检验
      beforeAvatarUpload (file) {
        const allowTypes = ['image/jpg', 'image/jpeg', 'image/png']
        const isLt2M = file.size / 1024 / 1024 < 3
        if (allowTypes.indexOf(file.type) === -1) {
          this.$message.warning('上传头像图片只能是 JPG/PNG/JPEG 格式!')
          return false
        }
        if (!isLt2M) {
          this.$message.warning('上传头像图片大小不能超过 3MB!')
          return false
        }
      },
      // 保存更改
      submitForm (form) {
        this.$refs[form].validate(valid => {
          if (valid) {
            this.saving = true
            if (this.userForm.avatar === env.baseUrl + '/sys/member/avatar/m/0') {
              this.userForm.avatar = null
            }
            this.editUser(this.userForm)
              .then(res => {
                if (res.data.code === 1) {
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  })
                }
              }).finally(() => {
                this.saving = false
              })
          }
        })
      },
      // 打开权限弹层
      handleOpenDialog () {
        if (this.$refs.AList) {
          this.$refs.AList.init()
        }
      }
    }
  }
</script>
<style lang="scss">
  .editUser{
    position:relative;
    padding-bottom:77px;
    .userForm{
      .avatar{display:block;width:90px;height:90px;border-radius:50%;border:1px solid #c2cdda}
      .upload{margin-left:15px;color:#23a2ff}
      .tips{color:#8492a6}
      .el-input__inner{max-width: 500px}
    }
    .auth-dialog{width:640px;}
    .auth-dialog .authList{height:618px;overflow-y: scroll}
    .bottom{position:absolute;bottom:0;left:0;width:100%;padding:20px 0;background:#fff;text-align:center;border-top:1px solid #e0e6ed;}
  }
</style>
